<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>canvas画图</title>
	<style>
		canvas{
			border:1px solid red;
		}
		span{
			display: inline-block;
			width: 46px;
			height: 46px;

		}
		.red{
			background-color: red;
			border:2px solid red;
		}
		.green{
			background-color: green;
			border:2px solid green;
		}
		.blue{
			background-color: blue;
			border:2px solid blue;
		}
		div{
			display: inline-block;
			border-radius: 50%;
			margin-right: 10px;
			background-color: black;
		}
		.lw10{
			width: 10px;
			height: 10px;
		}
		.lw20{
			width: 20px;
			height: 20px;
		}
		.lw30{
			width: 30px;
			height: 30px;
		}
	</style>
</head>
<body>
	<canvas width="1000" height="600" id="canvas"></canvas>
	<span class="red"></span>
	<span class="green"></span>
	<span class="blue"></span>
	<br>
	<div class="lw10"></div>
	<div class="lw20"></div>
	<div class="lw30"></div>
	<br>
	<button id="bt1">清空画布</button>
	
	<script>
		window.onload=function(){
			var myCanvas=document.getElementById('canvas');
			var cxt=myCanvas.getContext("2d");

			myCanvas.onmousedown=function(event){
				var x=event.clientX-myCanvas.offsetLeft;
				var y=event.clientY-myCanvas.offsetTop;
				cxt.beginPath();
				cxt.moveTo(x,y);
				myCanvas.onmousemove=function(event){
					var nx=event.clientX-myCanvas.offsetLeft;
					var ny=event.clientY-myCanvas.offsetTop;
					cxt.lineTo(nx,ny);
					cxt.stroke();
				}
				myCanvas.onmouseup=function(){
					myCanvas.onmousemove=null;
					cxt.closePath();
				}
				myCanvas.onmouseleave=function(){
					myCanvas.onmousemove=null;
					cxt.closePath();
				}
			}
			var spans=document.getElementsByTagName('span');
			for (var i = 0; i < spans.length; i++) {
				spans[i].onclick=function(){
					col=this.className;
					cxt.strokeStyle=col;
				}
			}

			var divs=document.getElementsByTagName('div');
			for (var i = 0; i < divs.length; i++) {
				divs[i].onclick=function(){
					var wids=this.offsetWidth;
					cxt.lineWidth=wids;
				}
			}

			var bt1=document.getElementById('bt1');
			bt1.onclick=function(){
				cxt.clearRect(0,0,myCanvas.width,myCanvas.height)
			}
		}
	</script>
</body>
</html>